﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Radiation___IM.ApiCommands
{
    public class AddFriend: ICommand
    {
        private readonly string m_commandkey = Radiation.Common.Communication.APIMethods.ADD_FRIEND;

        public AddFriend()
        {
        }

        public string commandKey()
        {
            return m_commandkey;
        }

        public string requiredPermission()
        {
            return "manage_friends";
        }

        public void execute(string[] commands, Client client)
        {
            if (Users.UserManager.Instance[client.Nickname] != null &&
                            commands.Length > 2 &&
                            commands[2].Length > 1) // if user is logged in and input valid
            {
                if (Users.UserManager.Instance[commands[2]] != null)
                {
                    if (Users.UserManager.Instance[client.Nickname].Friends.Contains(commands[2]))
                    {
                        MessageExecution.sendDataAPI(client,
                             Radiation.Common.Communication.Constants.ADDFRIEND_ALREADY_ADDED + ";",
                             commands[1]);
                    }
                    else
                    {
                        // Everything's fine
                        Users.UserManager.Instance[client.Nickname].Friends.Add(commands[2]);
                        MessageExecution.sendDataAPI(client,
                            Radiation.Common.Communication.Constants.ADDFRIEND_SUCCESS + ";" + commands[2],
                            commands[1]);
                        MessageExecution.sendDataAPI(client,
                             commands[2],
                             Radiation.Common.Communication.APIMethods.CLIENT_ADD_FRIEND);
                        Data.DatabaseWriter.Instance.Queue(Users.UserManager.Instance[client.Nickname].getFile());
                    }
                }
                else
                {
                    // the user does not exists
                    MessageExecution.sendDataAPI(client,
                        Radiation.Common.Communication.Constants.ADDFRIEND_ACCOUNT_NOT_FOUND + ";",
                        commands[1]);
                }
            }
            else
                MessageExecution.sendDataAPI(client,
                    Radiation.Common.Communication.Constants.ADDFRIEND_ERROR + ";",
                    commands[1]);
        }
    }
}
